package com.cgnpc.cuddemo.workbench.application.impl;

import com.cgnpc.cud.auth.api.IPermissionService;
import com.cgnpc.cud.auth.vo.Menu;
import com.cgnpc.cud.shiro.util.ContextHolder;
import com.cgnpc.cuddemo.workbench.application.IPermissonApplication;
import com.cgnpc.scp.common.utils.JacksonUtil;
import com.cgnpc.scp.common.utils.ListUtil;
import com.cgnpc.scp.common.utils.StringUtil;
import com.cgnpc.scp.config.MockClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class PermissonApplicationImpl implements IPermissonApplication {

    private static final Logger LOGGER = LoggerFactory.getLogger(PermissonApplicationImpl.class);

    private String devMode;

    @Value("${spring.profiles.usemock}")
    private void setDevMode(String dm) {
        devMode = dm;
    }

    @Autowired
    IPermissionService permissionService;

    /**********************************
     * 用途说明:获取用户的菜单权限
     * 参数说明
     * 返回值说明:
     ***********************************/
    @Override
    public Set<Menu> selectMenus(String s, String... strings) {
        return permissionService.selectMenus(ContextHolder.getPrincipalName(), ContextHolder.getProject());
    }

    /**********************************
     * 用途说明:获取用户的菜单权限(树形)
     * 参数说明
     * 返回值说明:
     ***********************************/
    @Override
    public List<Menu> selectMenusTree(String s, String... strings) {
        LOGGER.info("selectMenusTree：{}---{}",ContextHolder.getPrincipalName(), ContextHolder.getProject());
        Set<Menu> menus = permissionService.selectMenus(ContextHolder.getPrincipalName(), ContextHolder.getProject());
//        Set<Menu> menus = permissionService.selectMenus("P622400", ContextHolder.getProject());
        LOGGER.info("selectMenusTree menu count:{}",menus.size());
        Set<Menu> collect = menus.stream().filter(menu -> "001".equals(menu.getMenuType())).collect(Collectors.toSet());
        LOGGER.info("selectMenusTree menu count:{}",collect.size());
        List<Menu> menus1 = menuToTree(collect);
        return menus1;
    }

    /**********************************
     * 用途说明:获取读写权限
     * 参数说明
     * 返回值说明:
     ***********************************/
    @Override
    public Set<Menu> getWritePermission(String s, String... strings) {
        Set<Menu> menus = permissionService.selectMenus(ContextHolder.getPrincipalName(), ContextHolder.getProject());
        Set<Menu> collect = menus.stream().filter(menu -> "002".equals(menu.getMenuType())).collect(Collectors.toSet());
        return collect;
    }

    /**********************************
     * 用途说明:获取用户的角色
     * 参数说明
     * 返回值说明:
     ***********************************/
    @Override
    public Set<String> selectRoles(String s, String... strings) {
        if ("local".equals(devMode)) {
            String json = "[\"coordinationadmin\", \"hradmin\", \"sciadmin\", \"puradmin\", \"default_admin_auth\", \"sysadmin\", \"hseadmin\"]";
            return JacksonUtil.readValue(json,Set.class);
        }
        return permissionService.selectRoles(ContextHolder.getPrincipalName());
    }

    /**********************************
     * 用途说明: 是否具有某个角色
     * 参数说明 roleName
     * 返回值说明:
     ***********************************/
    @Override
    public boolean hasRoles(String roleName) {
        Set<String> roles = selectRoles(null);
        if(roles.contains(roleName)) {
            return true;
        }
        return false;
    }

    /**********************************
     * 用途说明:获取用户的其他权限
     * 参数说明
     * 返回值说明:
     ***********************************/
    @Override
    public Set<String> selectPermissions(String s, String... strings) {
        return permissionService.selectPermissions(ContextHolder.getPrincipalName(), ContextHolder.getProject());
    }

    /**********************************
     * 用途说明: 将菜单转为树形
     * 参数说明 menus
     * 返回值说明:
     ***********************************/
    @Override
    public List<Menu> menuToTree(Set<Menu> menus) {
        List<Menu> usedMenuList = new ArrayList<>(menus);

        if (ListUtil.getListSizeWith0(usedMenuList) <= 0) {
            return usedMenuList;
        }

        // begin 将List的每个对象添加到Map映射中
        Map<String, Menu> mapMenuAll = new HashMap<>();

        for (Menu usedMenu : usedMenuList) {
            mapMenuAll.put(usedMenu.getMenuId(), usedMenu);
        }
        // end 将List的每个对象添加到Map映射中

        final boolean needOrderByWithMenuCode = true;

        // begin 排序
        Collections.sort(usedMenuList, new Comparator<Menu>() {
            @Override
            public int compare(Menu o1, Menu o2) {
                if (o1 == null || o2 == null) {
                    return 1;
                }

                String o1MenuCode = o1.getMenuCode();
                String o2MenuCode = o2.getMenuCode();

                if (o1MenuCode != null && o2MenuCode != null) {
                    return o1MenuCode.compareTo(o2MenuCode);
                }

                if (needOrderByWithMenuCode) {
                    return 1;
                }

                String strO1OrderNum = o1.getOrderNum();
                String strO2OrderNum = o2.getOrderNum();

                if (StringUtil.isNumberSimpleString(strO1OrderNum)
                        && StringUtil.isNumberSimpleString(strO2OrderNum)
                ) {
                    double o1OrderNum = Double.parseDouble(strO1OrderNum);
                    double o2OrderNum = Double.parseDouble(strO2OrderNum);

                    if (o1OrderNum < o2OrderNum) {
                        return -1;
                    } else if (o1OrderNum == o2OrderNum) {
                        return 0;
                    } else {
                        return 1;
                    }
                }

                return 1;
            }
        });
        // end 排序

        // begin 构建成树
        String parentId = null;
        Menu parentMenu = null;
        List<Menu> tempMenuList = new ArrayList<>(usedMenuList);

        for (Menu tempMenu : tempMenuList) {
            parentId = tempMenu.getParentId();

            parentMenu = mapMenuAll.get(parentId);

            if (parentMenu != null) {
                List<Menu> parentMenuChildren = parentMenu.getChildren();

                if (parentMenuChildren == null) {
                    parentMenuChildren = new ArrayList<>();
                    parentMenu.setChildren(parentMenuChildren);
                }

                parentMenuChildren.add(tempMenu);
                usedMenuList.remove(tempMenu);
            }
        }
        // end 构建成树

        return usedMenuList;
    }
}